<?php


namespace App\Http\Controllers\WebApi;


use App\Http\Controllers\WebApi\Business\OperationLogsBusiness;
use App\Models\ImOperationLogs;
use App\Models\ImPayLogs;
use App\Models\ImUserBalance;
use App\Models\ImUsers;
use App\Validators\AuthValidator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class BalanceController
{
    /**
     * 零钱充值
     * @param Request $req
     * @return \Illuminate\Http\JsonResponse
     */
    public function recharge(Request $req)
    {
        $param = $req->all();
        $valid = AuthValidator::handle($param, 'recharge');
        if (true !== $valid) {
            return errBack($valid->first());
        }
        $user = ImUsers::find($param['user_id']);
        if (!$user) {
            return errBack('用户不存在');
        }
        DB::beginTransaction();
        try {
            //充值部分
            $balance = ImUserBalance::where('user_id', $param['user_id'])->lockForUpdate()->first();
            if (!$balance) {
                $userBalance = new ImUserBalance();
                $userBalance->user_id = $param['user_id'];
                $userBalance->money = $param['money'];
                $userBalance->save();
            } else {
                $balance->increment('money', $param['money']);
            }

            //记录用户流水
            $payLog = new ImPayLogs();
            $payLog->type = 1;
            $payLog->user_id = $param['user_id'];
            $payLog->money = $param['money'];
            $payLog->operator_id = $req->userInfo['id'];
            $payLog->describe = '零钱充值';
            $payLog->save();

            DB::commit();
            //添加操作日志
            OperationLogsBusiness::addLog(ImOperationLogs::UPDATE, '后台充值;用户ID:' .
                $param['user_id'] . ';金额:' . $param['money']);
            return okBack();
        } catch (\Exception $e) {
            DB::rollBack();
            Log::info($e->getMessage());
            return errBack('充值失败');
        }
    }

    /**
     * 零钱的冻结与解冻
     * @param Request $req
     * @return \Illuminate\Http\JsonResponse
     */
    public function setStatus(Request $req)
    {
        $param = $req->all();
        $valid = AuthValidator::handle($param, 'setBalanceStatus');
        if (true !== $valid) {
            return errBack($valid->first());
        }
        $user = ImUsers::find($param['user_id']);
        if (!$user) {
            return errBack('用户不存在');
        }
        DB::beginTransaction();
        try {
            $balance = ImUserBalance::where('user_id', $param['user_id'])->lockForUpdate()->first();
            $oldStatus = $balance->status;
            if (!$balance) {
                $userBalance = new ImUserBalance();
                $userBalance->user_id = $param['user_id'];
                $userBalance->money = 0;
                $userBalance->status = $param['status'];
                $userBalance->save();
            } else {
                $balance->status = $param['status'];
                $balance->save();
            }
            DB::commit();
            //添加操作日志
            if ($balance->status != $oldStatus) {
                OperationLogsBusiness::addLog(ImOperationLogs::UPDATE, ImUserBalance::getStatus(
                        $param['status']) . '用户余额;用户ID:' . $param['user_id']);
            }
            return okBack();
        } catch (\Exception $e) {
            DB::rollBack();
            Log::info($e->getMessage());
            return errBack('设置失败');
        }
    }

    /**
     * 支付日志，后台充值
     * @return \Illuminate\Http\JsonResponse
     */
    public function payLogs(Request $req)
    {
        $type = $req->get('type');
        $searchWord = $req->get('searchWord');
        $timeStart = $req->get('timeStart');
        $timeEnd = $req->get('timeEnd');
        list($offset, $limit, $page, $pagesize) = ImPayLogs::pageProcess();
        $query = ImPayLogs::with(['user' => function ($sql) {
            $sql->select(['id', 'nickname', 'phone']);
        }, 'operator' => function ($sql) {
            $sql->select(['id', 'username', 'phone']);
        }]);
        if ($type > 0) {
            $query->where('type', $type);
        }
        if ($searchWord) {
            $query->whereHas('user', function ($sql) use ($searchWord) {
                $sql->where('nickname', $searchWord)->orWhere('id', $searchWord);
            });
        }
        if (!empty($timeStart) && !empty($timeEnd)) {
            $query->whereBetween('created_at', [$timeStart, $timeEnd]);
        }
        $total = $query->count();
        $data = $query->offset($offset)->limit($limit)->orderBy('id', 'desc')->get();
        return okBack($data, [
            'total' => $total,
            'page' => $page,
            'pagesize' => $pagesize,
        ]);
    }
}
